package com.interfaces.module.user.controller;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.interfaces.aspect.auth.LoginAuth;
import com.interfaces.config.RedisCache;
import com.interfaces.enumeration.HTTP_STATUS_CODE_ENUM;
import com.interfaces.enumeration.TOKEN_TIME_TYPE;
import com.interfaces.enumeration.TOKEN_TYPE;
import com.interfaces.module.user.domain.FtsUser;
import com.interfaces.module.user.service.FtsUserService;
import com.interfaces.util.Result;
import com.interfaces.util.TokenUtil;
import com.interfaces.wx.WxAuthAccessToken;
import com.interfaces.wx.WxPayInit;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 微信公众号用户
 */
@RestController
@RequestMapping("/wxuser")
public class WxUserController {
    @Autowired
    private FtsUserService ftsUserService;
    @Autowired
    RedisCache cache;
    /**
     * 获取微信用户画像信息
     * @param code
     * @return
     */
    @LoginAuth
    @RequestMapping("/info")
    public Result info(String code){
        if(null==code){
            return Result.ERROR("code不存在==",404);
        }
        String nowDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

        WxAuthAccessToken wechatAuthAccessToken=new WxAuthAccessToken();
        JSONObject  userInfo=wechatAuthAccessToken.accessToken(code,cache);
        if(StringUtils.isNotEmpty(userInfo.getString("openid"))){
            //获取微信用户信息成功，进行注册
            String openid=userInfo.getString("openid");
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("open_id",openid);
            FtsUser ftsUser=ftsUserService.getOne(queryWrapper);
            if(null==ftsUser){
                ftsUser=new FtsUser();
                ftsUser.setOpenId(openid);
                ftsUser.setNickName(userInfo.getString("nickname"));
                ftsUser.setGender(userInfo.getInteger("sex"));
                ftsUser.setAvatar(userInfo.getString("headimgurl"));
                ftsUser.setProvince(userInfo.getString("province"));
                ftsUser.setCity(userInfo.getString("city"));
                ftsUser.setCountry(userInfo.getString("country"));
                ftsUser.setUnionId(userInfo.getString("unionid"));
                ftsUser.setRegisterTime(nowDate);
                ftsUserService.saveOrUpdate(ftsUser);

            }
            return Result.SUCCESS(ftsUser);
        }else{
            return Result.ERROR("获取微信画像失败，请联系管理员",userInfo);
        }

    }

    /**
     * 同步微信信息
     * @param code
     * @return
     */
    @LoginAuth
    @RequestMapping("/sycnWxInfo")
    public Result sycnWxInfo(String code){
        if(null==code){
            return Result.ERROR("code不存在==",404);
        }
        String nowDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

        WxAuthAccessToken wechatAuthAccessToken=new WxAuthAccessToken();
        JSONObject  userInfo=wechatAuthAccessToken.accessToken(code,cache);
        if(StringUtils.isNotEmpty(userInfo.getString("openid"))){
            //获取微信用户信息成功，进行注册
            String openid=userInfo.getString("openid");
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("open_id",openid);
            FtsUser ftsUser=ftsUserService.getOne(queryWrapper);
            ftsUser.setOpenId(openid);
            ftsUser.setNickName(userInfo.getString("nickname"));
            ftsUser.setGender(userInfo.getInteger("sex"));
            ftsUser.setAvatar(userInfo.getString("headimgurl"));
            ftsUser.setProvince(userInfo.getString("province"));
            ftsUser.setCity(userInfo.getString("city"));
            ftsUser.setCountry(userInfo.getString("country"));
            ftsUser.setUnionId(userInfo.getString("unionid"));
            ftsUser.setRegisterTime(nowDate);
            ftsUserService.saveOrUpdate(ftsUser);
            return Result.SUCCESS(ftsUser);
        }else{
            return Result.ERROR("获取微信画像失败，请联系管理员",userInfo);
        }

    }
    /**
     * 根据用户信息进行登录
     * @return
     */
    @LoginAuth
    @RequestMapping("/login")
    public Result login(@RequestBody FtsUser user){
        if(null==user.getOpenId()||user.getOpenId().length()<1){
            return Result.ERROR(HTTP_STATUS_CODE_ENUM.TOKEN_UNAUTHORIZED);
        }
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("open_id",user.getOpenId());
        String nowDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        FtsUser ftsUser=ftsUserService.getOne(queryWrapper);
        user.setLastLoginTime(nowDate);
        String token= UUID.randomUUID().toString().replaceAll("-","");

        if(null==ftsUser){
            user.setRegisterTime(nowDate);

        }else{
            user=ftsUser;

        }
        user.setToken(token);
        ftsUserService.saveOrUpdate(user,queryWrapper);
        cache.putCacheObject(token,user, TokenUtil.cacheTime,TimeUnit.valueOf(TokenUtil.expireType));
        return Result.SUCCESS(user);
    }
}
